<template>
	<div class="dashboard">
		<Row type="flex" class="statistics" :gutter="20" justify="center">
			<Col class="item" span="4">
				<div>
					<span class="icon-tag">
						<img :width="32" :height="32" :src="require('@images/d1.png')" alt />
					</span>
					<h2>{{vipCount}}</h2>
					<span>会员数量</span>
				</div>
			</Col>
			<Col class="item" span="4">
				<div>
					<span class="icon-tag">
						<img :width="32" :height="32" :src="require('@images/d2.png')" alt />
					</span>
					<h2>{{interventionCount}}</h2>
					<span>干预次数</span>
				</div>
			</Col>
			<Col class="item" span="4">
				<div>
					<span class="icon-tag">
						<img :width="32" :height="32" :src="require('@images/d3.png')" alt />
					</span>
					<h2>{{followCount}}</h2>
					<span>随访次数</span>
				</div>
			</Col>
			<Col class="item" span="4">
				<div>
					<span class="icon-tag">
						<img :width="32" :height="32" :src="require('@images/d4.png')" alt />
					</span>
					<h2>{{watchCount}}</h2>
					<span>监测记录</span>
				</div>
			</Col>
			<Col class="item" span="4">
				<div>
					<span class="icon-tag">
						<img :width="32" :height="32" :src="require('@images/d5.png')" alt />
					</span>
					<h2>{{warningCount}}</h2>
					<span>健康预警</span>
				</div>
			</Col>
			<Col class="item" span="4">
				<div>
					<span class="icon-tag">
						<img :width="32" :height="32" :src="require('@images/d6.png')" alt />
					</span>
					<h2>{{activeVipCount}}</h2>
					<span>活跃会员</span>
				</div>
			</Col>
		</Row>

		<Row type="flex" class="block" :gutter="20">
			<Col class="section section1" span="12">
				<h3 class="chart-title">
					<div>
						<span class="icon-tag">
							<img :width="32" :height="32" :src="require('@images/d11.png')" alt />
						</span>用户画像分析
					</div>
				</h3>
				<div class="chart chart1">
					<Row type="flex" align="middle">
						<Col :span="8">
							<div>
								<Row class="sex-line" type="flex" align="middle">
									<img class="ml20" :width="50" :height="50" :src="require('@images/men.png')" alt />
									<span
										class="ml20"
									>男性 {{sexStatList[0]['count']}}人（{{(sexStatList[0]['count']/(sexStatList[0]['count']+sexStatList[1]['count']) * 100).toFixed(2)}}%）</span>
								</Row>
							</div>
							<div class="mt30">
								<Row type="flex" align="middle">
									<img class="ml20" :width="50" :height="50" :src="require('@images/women.png')" alt />
									<span
										class="ml20"
									>女性 {{sexStatList[1]['count']}}人（{{(sexStatList[1]['count']/(sexStatList[0]['count']+sexStatList[1]['count']) * 100).toFixed(2)}}%）</span>
								</Row>
							</div>
						</Col>
						<Col :span="8" align="center">
							<div id="sexChart" />
						</Col>
						<Col :span="8">
							<div class="ml20">
								<Row class="lh300" v-for="(item,i) in ageStatList" :key="i">
									<Col :span="8">
										<i :class="['dot','dot'+i]" />
										{{item.age}}岁
									</Col>
									<Col :span="8">{{(item.count/ageTotalNum*100).toFixed(2)}}%</Col>
									<Col :span="8">{{item.count || 0}}人</Col>
								</Row>
							</div>
						</Col>
					</Row>
				</div>
			</Col>
			<Col class="section section2" span="12">
				<h3 class="chart-title">
					<div>
						<span class="icon-tag">
							<img :width="32" :height="32" :src="require('@images/d12.png')" alt />
						</span>预警异常分析
					</div>
                    <div class="tab">
						<RadioGroup
							:loading="warningResolutionLoading"
							size="small"
							:value="warningResolution"
							type="button"
							@on-change="t=>statQueryListByGroups(t)"
						>
							<Radio :label="7">最近一周</Radio>
							<Radio :label="30">最近一月</Radio>
							<Radio :label="90">最近三月</Radio>
							<Radio :label="180">最近半年</Radio>
						</RadioGroup>
					</div>
				</h3>
				<div class="chart chart2">
					<div class="chart-line" v-for="(item,i) in chart2Data" :key="i">
						<strong>{{item.name}}</strong>
						<div>
							<div :class="['path','path' + i]" :style="{width:item.totalCount/chart2Total*200+'%'}" />
							<span class="ml20">{{item.totalCount}}次（{{(item.totalCount/chart2Total*100).toFixed(2)}}%）</span>
						</div>
					</div>
				</div>
			</Col>
		</Row>

		<Row type="flex" class="block" :gutter="20">
			<Col class="section section3" span="12">
				<h3 class="chart-title">
					<div>
						<span class="icon-tag">
							<img :width="32" :height="32" :src="require('@images/d13.png')" alt />
						</span>会员新增趋势
					</div>
					<div class="tab">
						<RadioGroup
							:loading="interventionResolutionLoading"
							size="small"
							:value="interventionResolution"
							type="button"
							@on-change="interventionResolutionChange"
						>
							<Radio :label="7">最近一周</Radio>
							<Radio :label="30">最近一月</Radio>
							<Radio :label="90">最近三月</Radio>
							<Radio :label="180">最近半年</Radio>
						</RadioGroup>
					</div>
				</h3>
				<div class="chart chart3" id="interventionChart"></div>
			</Col>
			<Col class="section section4" span="12">
				<h3 class="chart-title">
					<div>
						<span class="icon-tag">
							<img :width="32" :height="32" :src="require('@images/d14.png')" alt />
						</span>会员消费趋势
					</div>
					<div class="tab">
						<RadioGroup size="small" type="button">
							<Radio :label="7">最近一周</Radio>
							<Radio :label="30">最近一月</Radio>
							<Radio :label="90">最近三月</Radio>
							<Radio :label="180">最近半年</Radio>
						</RadioGroup>
					</div>
				</h3>
				<div class="chart chart4">
					<div id="buyChart" />
				</div>
			</Col>
		</Row>
		<div class="footer">Copyright © 2019 深圳市科信康科技有限公司</div>
	</div>
</template>
<script>
import { customerPageQueryList, customerQueryAgeAndSexStat } from '@api/customer.js'
import { createChart } from 'lightweight-charts'
import { statStat, statPageQueryList, statQueryListByGroup, statQueryListByGroups } from '@api/stat.js'
import { mapState } from '@lib/x_.js'
import echarts from '@lib/echart.js'
import moment from 'moment'
export default {
	data() {
		return {
            chart2Total: 1,
            ageTotalNum: 1,
			chart2Data: [],
			amountData: [{ y: '2006', a: 100, width: 10 }, { y: '2007', a: 75 }, { y: '2008', a: 50 }, { y: '2009', a: 75 }, { y: '2010', a: 50 }, { y: '2011', a: 75 }, { y: '2012', a: 100 }, { y: '2012', a: 100 }, { y: '2012', a: 100 }, { y: '2012', a: 100 }, { y: '2012', a: 100 }, { y: '2012', a: 100 }],
			sexStatList: [
				{
					sex: 0,
					age: 0,
					count: 1
				},
				{
					sex: 0,
					age: 0,
					count: 1
				}
			],
			colors: ['#1989FA', '#36CBCB', '#4ECB73', '#FACC14'],
            ageStatList: [],
            warningResolution: 7,
            warningResolutionLoading: false,
			interventionResolution: 7,
			interventionResolutionLoading: false,
			followResolution: 7,
			followResolutionLoading: false,

			interventionLineSeries: null,
			followSeries: null,

			/**最顶部数量 */
			vipCount: '-',
			watchCount: '-',
			warningCount: '-',
			activeVipCount: '-',
			interventionCount: '-',
			followCount: '-'
		}
	},
	created() {
		this.statStat()
		this.interventionStatPageQueryList(7)
		this.customerQueryAgeAndSexStat()
		this.statQueryListByGroups(7)
	},
	mounted() {
		this.initChart()
	},
	computed: {
		...mapState(['user'])
	},
	methods: {
        
		initSexChart(data) {
			var dom = document.getElementById('sexChart')
			var myChart = echarts.init(dom)
			var option = {
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b}: {c}个 ({d}%)'
				},
				color: this.colors,
				series: [
					{
						name: '年龄分布',
						type: 'pie',
						radius: ['50%', '70%'],
						avoidLabelOverlap: false,
						label: {
							normal: {
								show: false,
								position: 'center'
							},
							emphasis: {
								show: true,
								textStyle: {
									fontSize: '12'
								}
							}
						},
						labelLine: {
							normal: {
								show: false
							}
						},
						data: data
					}
				]
			}
			if (option && typeof option === 'object') {
				myChart.setOption(option, true)
			}
		},
		initBuyChart(data) {
			var dom = document.getElementById('buyChart')
			var myChart = echarts.init(dom)
			var option = {
				color: this.colors,
				tooltip: {
					trigger: 'axis',
					axisPointer: {
						// 坐标轴指示器，坐标轴触发有效
						type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
					}
				},
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
                },
				xAxis: [
					{
						type: 'category',
						data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
						axisTick: {
							alignWithLabel: true
						}
					}
				],
				yAxis: [
					{
						type: 'value'
					}
				],
				series: [
					{
						name: '消费金额',
						type: 'bar',
						barWidth: '40%',
						data: [10, 52, 200, 334, 390, 330, 220]
					}
				]
			}

			if (option && typeof option === 'object') {
				myChart.setOption(option, true)
			}
		},
		statQueryListByGroups(day) {
            const beginStatDate =  moment(+new Date() - day*86400000).format('YYYY-MM-DD HH:mm:ss');
            const endStatDate =  moment(+new Date()).format('YYYY-MM-DD HH:mm:ss');
            console.log("beginStatDate>", beginStatDate)
            console.log("endStatDate>", endStatDate)
			statQueryListByGroups({
                bizCodes: ['uric', 'copd', 'fat', 'pressure', 'sugar'],
                beginStatDate,
                endStatDate,
			}).then(res => {
				console.log('statQueryListByGroup>', res)
				if (res.code === '0') {
					const names = ['尿酸', '呼吸', '血脂', '血压', '血糖']
					const arr = []
					let total = 0
					res.data.map((item, i) => {
						res.data[i]['name'] = names[i]
						total += item.totalCount
					})
					this.chart2Total = total
					this.chart2Data = res.data
				}
			})
		},
		customerQueryAgeAndSexStat() {
			customerQueryAgeAndSexStat().then(res => {
				if (res.code === '0') {
					const { sexStatList, ageStatList } = res.data
					this.sexStatList = sexStatList
                    console.log('sexStatList>', sexStatList)
                    let total = 0;
                    ageStatList.map((item,i) => {
                        total+= item.count;
                    })
                    this.ageTotalNum = total;
					this.ageStatList = ageStatList
					const arr = []

					ageStatList.map((item, i) => {
						arr.push({ name: item.age + '岁', value: item.count, color: this.colors[i] })
					})
                    this.initSexChart(arr)
                    this.initBuyChart()
				}
			})
		},
		interventionResolutionChange(r) {
			this.interventionStatPageQueryList(r)
		},
		interventionStatPageQueryList(size) {
			if (this.interventionResolutionLoading) return
			this.interventionResolutionLoading = true
			statPageQueryList({ page: 1, pageSize: size, bizCode: 'customer_intervention' })
				.then(res => {
					this.interventionResolutionLoading = false
					if (res.code === '0') {
						const { items, pageSize } = res.data
						this.interventionResolution = pageSize
						items.map((item, i) => {
							item['time'] = item.statDate
							item['value'] = item.totalCount
						})
						console.log('interventionLineSeries data-->', items)
						this.interventionLineSeries.setData(items)
					}
				})
				.catch(err => {
					this.interventionResolutionLoading = false
				})
		},

		statStat() {
			statStat({ bizCodes: ['customer_intervention', 'customer_follow', 'fat_hdl_higher', 'fat_hdl_lower', 'fat_ldl_higher', 'fat_ldl_lower', 'fat_tc_higher', 'fat_tc_lower', 'fat_tg_higher', 'fat_tg_lower', 'pressure_higher', 'pressure_lower', 'sugar_higher', 'sugar_lower', 'uric_higher', 'uric_lower'] }).then(res => {
				if (res.code === '0') {
					let [interventionCount, followCount] = res.data
					interventionCount = interventionCount.totalCount
					followCount = followCount.totalCount
					this.interventionCount = interventionCount
					this.followCount = followCount
					let warningCount = 0
					res.data.map((item, i) => {
						if (i > 1) {
							warningCount += item.totalCount
						}
					})
					this.warningCount = warningCount
				}
			})

			statStat({ bizCodes: ['pressure', 'fat', 'uric', 'copd', 'sugar'] }).then(res => {
				if (res.code === '0') {
					let watchCount = 0
					res.data.map((item, i) => {
						if (i > 1) {
							watchCount += item.totalCount
						}
					})
					this.watchCount = watchCount
				}
			})

			customerPageQueryList({ page: 1, pageSize: 1 }).then(res => {
				console.log('res-->', res)
				if (res.code === '0') {
					this.activeVipCount = res.data.totalNum
				}
			})
		},

		initChart() {
			const interventionChart = createChart(document.getElementById('interventionChart'), {
				priceScale: {
					scaleMargins: {},
					position: 'left',
					borderVisible: false
				},
				grid: {
					horzLines: {
						color: '#fff'
					},
					vertLines: {
						color: '#fff'
					}
				},
				width: document.querySelector('.chart').offsetWidth - 20,
				height: document.querySelector('.chart').offsetHeight
			})
			const interventionLineSeries = interventionChart.addAreaSeries({
				topColor: '#D5E8FC',
				bottomColor: '#D5E8FC',
				lineColor: '#2D8CF0',
				lineWidth: 2
			})
			this.interventionLineSeries = interventionLineSeries
			interventionLineSeries.setData([])
		}
	}
}
</script>
<style lang="scss">
.dashboard {
	position: relative;
	padding: 0 !important;
	height: 100%;
	display: flex;
	flex-direction: column;
	.block {
		flex: 1;
	}
	.chart {
		background-color: #fff;
		flex: 1;
	}
	.icon-tag {
		height: 32px;
		width: 32px;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.footer {
		line-height: 300%;
		text-align: center;
	}
	#sexChart {
		min-height: 200px;
	}
    #buyChart {
        height: 100%;
    }
	.statistics {
		text-align: center;
		.item {
			text-align: center;
			div {
				display: flex;
				flex-direction: column;
				align-items: center;
				padding-top: 10px;
				padding-bottom: 10px;
				background-color: #fff;
			}
		}
		h2 {
			font-size: 28px;
			color: #515a6e;
			font-weight: bold;
		}
	}
	.table {
		margin-top: 20px;
		.item {
			> div {
				background-color: #fff;
			}
		}
		.ivu-table th {
			background-color: #fff;
			border-top: 1px solid #e3e8ee;
		}
		.ivu-table-wrapper {
			border: 0 none;
			min-height: 330px;
		}
		.ivu-table:after {
			display: none;
		}
		h3 {
			line-height: 50px;
			padding-left: 10px;
			display: flex;
			align-items: center;
			span {
				margin-right: 10px;
			}
		}
	}
	.dot {
		width: 10px;
		height: 10px;
		border-radius: 5px;
		background-color: gray;
		position: relative;
		top: 1px;
		margin-right: 5px;
	}
	.dot0 {
		background-color: #1989fa;
		white-space: nowrap;
	}
	.dot1 {
		background-color: #13c2c2;
	}
	.dot2 {
		background-color: #2fc25b;
	}
	.dot3 {
		background-color: #facc14;
	}

	.chart-title {
		padding-left: 15px;
		background-color: #fff;
		display: flex;
		justify-content: space-between;
		border-bottom: 1px solid #d7dde4;
		align-items: center;
		div:nth-child(1) {
			display: flex;
			justify-content: flex-start;
			height: 50px;
			line-height: 50px;
			img {
				margin-top: 18px;
				margin-right: 10px;
			}
		}
		.tab {
			margin-right: 20px;
			position: relative;
			top: 14px;
		}
	}
	.section {
		height: 100%;
		display: flex;
		flex-direction: column;
		padding-top: 20px;
		.chart {
			flex: 1;
		}
	}
	.chart1 {
		> div {
			height: 100%;
		}
	}
	.chart2 {
		display: flex;
		flex-direction: column;
		justify-content: space-around;
		padding-left: 30px;
		padding-top: 30px;
		padding-bottom: 30px;
		strong {
			width: 60px;
			font-size: 14px;
			font-weight: normal;
		}
	}
	.chart-line {
		display: flex;
		> div {
			flex: 1;
			display: flex;
			justify-self: flex-start;
			line-height: 20px;
			.path {
				height: 20px;
				background-color: #3aa0ff;
                width: 60%;
                transition: width 0.2s linear;
			}
			.path1 {
				background-color: #13c2c2;
			}
			.path2 {
				background-color: #2fc25b;
			}
			.path3 {
				background-color: #facc14;
			}
			.path4 {
				background-color: #f2637b;
			}
		}
	}
}
</style>